<?php

namespace App\Http\Controllers\Apps;

use App\Http\Controllers\AppController;
use App\Http\Controllers\Controller;
use App\Http\Resources\Apps\OrderResource;
use App\Http\Resources\Apps\ProductResource;
use App\Http\Resources\Apps\UserInfoResource;
use App\Models\AppUser;
use App\Models\AppUserAddress;
use App\Models\AppUserBank;
use App\Models\AppUsersFile;
use App\Models\AppUserSmsCode;
use App\Services\AliSms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class User extends AppController
{
    public function sendCode(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'mobile'    => 'required|integer',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1);
        }

        $sms_code = AppUserSmsCode::where('mobile',$post['mobile'])->latest()->first();

        if ($sms_code && strtotime($sms_code->created_at) > time()+60){

            return $this->ReturnVerifyError(5); //发送频繁
        }

        $code = rand(1000,9999);

        $send = AliSms::sendCode($post['mobile'],1,['code'=>$code]);

        if ($send['Code'] != 'OK'){

            return $this->ReturnVerifyError(4,$send['Message']);//发送失败
        }

        AppUserSmsCode::create([
            'mobile'    => $post['mobile'],
            'code'      => $code
        ]);

        return $this->ReturnSuccessInfo();
    }

    public function register(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'mobile'    => 'required|integer',
            'password'  => 'required',
            'code'      => 'required|integer',
            'invite'    => 'sometimes|required|integer',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        if (AppUser::where('mobile',$post['mobile'])->exists()){

            return $this->ReturnVerifyError(103);
        }

        if ($request->filled('invite')){
            if (AppUser::where('mobile',$post['invite'])->doesntExist()){

                return $this->ReturnVerifyError(104);
            }
        }

        if ($verifyCode = $this->verifySmsCode($post['mobile'],$post['code'])){

            //return $this->ReturnVerifyError($verifyCode);
        }


        AppUser::create([
            'mobile'    => $post['mobile'],
            'password'  => Hash::make($post['password']),
            'invite'    => $request->filled('invite') ? $post['invite'] : '',
            'icon'      => Controller::$user_icon[1],
            'nickname'  => $post['mobile'],
        ]);

        return $this->ReturnSuccessInfo();
    }

    public function login(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'mobile'    => 'required|integer',
            'password'  => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        if (! $token = $this->auth()->attempt($validator->validated())){

            return $this->ReturnVerifyError(1);
        }

        return $this->ReturnSuccessInfo([
            'token' => $token,
            'type'  => 'bearer',
            'expire'=> $this->auth()->factory()->getTTL() * 60,
            'user_info' => UserInfoResource::make($this->auth()->user()),
        ]);
    }

    public function forget(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'mobile'    => 'required|integer',
            'code'      => 'required|integer',
            'password'  => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        $user = AppUser::where('mobile',$post['mobile']);

        if ($user->doesntExist()){

            return $this->ReturnVerifyError(105);
        }

        if ($verifyCode = $this->verifySmsCode($post['mobile'],$post['code'])){

            //return $this->ReturnVerifyError($verifyCode);
        }

        $flag = $user->first();
        $flag->password = Hash::make($post['password']);
        $flag->save();

        return $this->ReturnSuccessInfo();
    }

    public function address(Request $request)
    {
        $elem = AppUserAddress::latest()
                ->where('user_id',$this->auth()->id());

        $data = $elem->paginate($request->input('num',10));

        return $this->ReturnPage($data);
    }

    public function addressPost(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'    => 'required|integer',
            'name'  => 'required',
            'mobile'=> 'required|integer',
            'address' => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        AppUserAddress::updateOrCreate(['id'=>$post['id'],'user_id'=>$this->auth()->id()],$post);

        return $this->ReturnSuccessInfo();
    }

    public function addressDelete(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'    => 'required|exists:app_user_addresses,id',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        AppUserAddress::destroy($post['id']);

        return $this->ReturnSuccessInfo();
    }

    public function bank(Request $request)
    {
        $bank = AppUserBank::firstOrCreate(['user_id'=>$this->auth()->id()]);

        return $this->ReturnSuccessInfo($bank);
    }

    public function bankPost(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'name'      => 'required',
            'bank_card' => 'required|integer',
            'bank_name' => 'required',
            'bank_address'  => 'required',
            'mobile'    => 'required',
            'code'      => 'required|integer',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        AppUserBank::updateOrCreate(['user_id'=>$this->auth()->id()],$post);

        return $this->ReturnSuccessInfo();
    }

    public function infoEdit(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'icon'      => 'sometimes|required',
            'nickname'  => 'sometimes|required',
        ]);

        AppUser::find($this->auth()->id())
                ->update($validator->validated());

        return $this->ReturnSuccessInfo();
    }

    public function passwordEdit(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'old_password'  => 'required',
            'password'      => 'required|confirmed'
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        $user = AppUser::find($this->auth()->id());

        if (! Hash::check($post['old_password'],$user->password)){

            return $this->ReturnVerifyError(106);
        }

        $user->password = Hash::make($post['password']);
        $user->save();

        return $this->ReturnSuccessInfo();
    }

    public function team(Request $request)
    {
        $elem = AppUser::where('invite',$this->auth()->user()->mobile)
                ->latest();

        return $this->ReturnSuccessInfo([
            'list'  => $elem->get(),
        ]);
    }

    public function payPasswordEdit(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'password'  => 'required|confirmed',
            'code'      => 'required|integer',
            'mobile'    => 'required|integer',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        if ($verifyCode = $this->verifySmsCode($post['mobile'],$post['code'])){

            //return $this->ReturnVerifyError($verifyCode);
        }

        $user = AppUser::find($this->auth()->id());

        $user->pay_password = Hash::make($post['password']);
        $user->save();

        return $this->ReturnSuccessInfo();
    }

    public function transfer(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'mobile'    => 'required|integer',
            'balance'   => 'required|integer',
            'pay_password'  => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        if (! Hash::check($post['pay_password'],$this->auth()->user()->pay_password)){

            return $this->ReturnVerifyError(27);
        }

        $user = AppUser::where('mobile',$post['mobile'])->first();

        if (! $user){

            return $this->ReturnVerifyError(105);
        }

        $self = AppUser::find($this->auth()->id());

        if ($self->balance < $post['balance']){

            return $this->ReturnVerifyError(12);
        }

        $user->balance = $user->balance + $post['balance'];
        $user->save();

        $self->balance = $self->balance - $post['balance'];
        $self->save();

        return $this->ReturnSuccessInfo();
    }

    public function myBuy(Request $request)
    {
        $elem = \App\Models\Order::latest()
            ->where('status','<',2)
            ->where('buy_user_id',$this->auth()->id());

        $data = $elem->paginate($request->input('num',10));


        return $this->ReturnPage(OrderResource::collection($data));
    }

    public function mySale(Request $request)
    {
        $elem = \App\Models\Product::latest()
                ->where('user_id',$this->auth()->id());

        $data = $elem->paginate($request->input('num',10));

        return $this->ReturnPage(ProductResource::collection($data));
    }

    public function saleTransfer(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'product_id'    => 'required|integer'
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        $product = \App\Models\Product::where('id',$post['product_id'])
                    ->where('user_id',$this->auth()->id())->first();

        if (! $product){

            return $this->ReturnVerifyError(25);
        }

        $product->transfer = 1;
        $product->save();

        return $this->ReturnSuccessInfo();
    }

    public function upload(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'image'     => 'required|image|max:1024',
        ]);

        if ($validator->fails()){

            return $this->ReturnVerifyError(6,$validator->errors());
        }

        $file = $request->file('image');

        if ($file->isValid()){

            $path = $file->store('users/images/'.$this->auth()->user()->id,'public');

            $info = pathinfo($path);

            $row = AppUsersFile::create([
                'user_id'   => $this->auth()->id(),
                'name'      => $info['filename'],
                'path'      => $path,
                'url'       => Storage::url($path),
                'size'      => $file->getSize(),
                'mime'      => $file->getMimeType(),
            ]);

            return $this->ReturnSuccessInfo([
                'id'    => $row->id,
                'src'   => $row->url,
            ]);
        }

        return $this->ReturnFailed(1);
    }


}
